package cgl.narada.service.security.kmc;

import java.io.IOException;
import java.io.Serializable;
import java.security.cert.Certificate;
import java.util.Calendar;
import java.util.TimeZone;

import org.apache.log4j.Logger;

import cgl.narada.util.ObjectMarshaller;

/**
 * Security token. It comprises of the following
 * <ul>
 * <li>Client Certificate, (X.509 digital certificate)</li>
 * <li>Rights (publish/subscribe/some other ?/all OR a combination etc...)</li>
 * <li>Validty of this token</li>
 * </ul>
 * <br>
 * Created on Sep 8, 2005
 * 
 * @author Harshawardhan Gadgil (hgadgil@grids.ucs.indiana.edu)
 */
public class SecurityToken implements Serializable {

    static Logger log = Logger.getLogger("SecurityToken");

    /** Client certificate */
    private Certificate topicOwnerCertificate;

    /** Topic Rights */
    private TopicRights rights;

    /** Validity */
    private Calendar validity;

    public SecurityToken(Certificate _cert, TopicRights _rights,
            Calendar _validity) {
        topicOwnerCertificate = _cert;
        rights = _rights;
        validity = _validity;
    }

    /**
     * Marshalls the object into an array of bytes.
     * 
     * @return an array of bytes representing the marshaller object, null if
     *         error occurs
     */
    public byte[] getBytes() {
        try {
            return ObjectMarshaller.marshall(this);
        } catch (IOException e) {
            log.error("", e);
            return null;
        }
    }

    /**
     * Unmarshalls the bytes as a SecurityToken object
     * 
     * @param objectBytes
     * @return SecurityToken if successful, null if error occurs
     */
    public static SecurityToken createObjectFromBytes(byte[] objectBytes) {
        try {
            return (SecurityToken) ObjectMarshaller.unmarshall(objectBytes);
        } catch (IOException e) {
            log.error("", e);
        } catch (ClassNotFoundException e) {
            log.error("", e);
        }
        return null;
    }

    /**
     * Check if the validity of the token is sometime in the future
     * 
     * @return TRUE if validity is until sometime in future, FALSE otherwise.
     */
    public boolean isValid() {
        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT-5"));
        return validity.after(now);
    }

    /**
     * @return Returns the topicOwnerCertificate.
     */
    public Certificate getTopicOwnerCertificate() {
        return topicOwnerCertificate;
    }

    /**
     * @return Returns the rights.
     */
    public TopicRights getRights() {
        return rights;
    }

    /**
     * @return Returns the validity.
     */
    public Calendar getValidity() {
        return validity;
    }
}
